package untils

import (
	"fmt"
	"seckill-srv/basic/config"
	"time"
)

// 添加锁
func AddLock(activityId int, startTime time.Time) bool {
	// 计算当前时间到秒杀开始时间的时间间隔
	until := time.Until(startTime)
	if until <= 0 {
		return false // 开始时间已过，无法设置锁
	}
	lockKey := fmt.Sprintf("activity_%d_lock", activityId)
	result, err := config.Rdb.SetNX(config.Ctx, lockKey, 1, until).Result()
	if err != nil {
		return false
	}
	return result
}

// 释放锁
func DeleteLock(activityId int) bool {
	lockKey := fmt.Sprintf("activity_%d_lock", activityId)
	_, err := config.Rdb.Del(config.Ctx, lockKey).Result()
	if err != nil {
		return false
	}
	return true
}

// 添加用户锁
func AddUserLock(userId int) bool {
	lockKey := fmt.Sprintf("user_%d_lock", userId)
	result, err := config.Rdb.SetNX(config.Ctx, lockKey, 1, time.Second*2).Result()
	if err != nil {
		return false
	}
	return result
}

// 释放用户锁
func DeleteUserLock(userId int) bool {
	lockKey := fmt.Sprintf("user_%d_lock", userId)
	_, err := config.Rdb.Del(config.Ctx, lockKey).Result()
	if err != nil {
		return false
	}
	return true
}
